<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
use Overtrue\Pinyin\Pinyin;

class Bar extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'slug',
        'avatar',
        'description',
        'member_count',
        'post_count',
        'owner_id',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'member_count' => 'integer',
        'post_count' => 'integer',
    ];

    /**
     * Get the route key for the model.
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($bar) {
            if (empty($bar->slug)) {
                $bar->slug = static::generateSlug($bar->name);
            }
        });

        static::updating(function ($bar) {
            // 如果名称改变且 slug 为空，重新生成 slug
            if ($bar->isDirty('name') && empty($bar->slug)) {
                $bar->slug = static::generateSlug($bar->name);
            }
        });
    }

    /**
     * 生成 slug（使用拼音转换）
     */
    public static function generateSlug(string $name): string
    {
        $pinyin = new Pinyin();
        // 使用 permalink 方法，自动转换为拼音并用连字符分隔
        $pinyinSlug = $pinyin->permalink($name, '-');
        
        // 如果转为空（纯特殊字符），使用随机字符串
        if (empty($pinyinSlug)) {
            $pinyinSlug = 'bar-' . Str::random(12);
        }
        
        // 限制长度（URL 友好）
        $pinyinSlug = Str::limit($pinyinSlug, 100, '');
        
        // 确保唯一性（精确匹配，数据库已有唯一约束作为最终保障）
        $slug = $pinyinSlug;
        $counter = 1;
        $maxAttempts = 100; // 防止无限循环
        while ($counter <= $maxAttempts && static::where('slug', $slug)->exists()) {
            $slug = $pinyinSlug . '-' . $counter;
            $counter++;
        }
        
        // 如果达到最大尝试次数仍未找到唯一值，添加随机后缀
        if ($counter > $maxAttempts) {
            $slug = $pinyinSlug . '-' . Str::random(8);
        }
        
        return $slug;
    }

    /**
     * 贴吧拥有者（吧主）
     */
    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    /**
     * 贴吧成员
     */
    public function members(): HasMany
    {
        return $this->hasMany(BarMember::class);
    }

    /**
     * 判断用户是否为吧主
     */
    public function isOwner(User $user): bool
    {
        return $this->owner_id === $user->id;
    }

    /**
     * 判断用户是否为成员
     */
    public function isMember(User $user): bool
    {
        return $this->members()->where('user_id', $user->id)->exists();
    }

    /**
     * 贴吧的帖子
     */
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}
